﻿using AutoMapper;
using AyFrame.DbEntity.Models;
using AyFrame.Dto;
using AyFrame.IServices;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AyFrame.Services
{
    public class GatewayService : BaseService<OcelotGateway>, IGatewayService
    {
        readonly IMapper _mapper;
        public GatewayService(IMapper mapper)
        {
            _mapper = mapper;
        }

        public async Task<OcelotGatewayView> Add(string curUserId, OcelotGatewayCreateDto dto)
        {
            var entity = await GetSingleAsync(t => t.UpstreamPathTemplate.ToUpper() == dto.UpstreamPathTemplate.ToUpper()
                 || t.DownstreamPathTemplate == dto.DownstreamPathTemplate);

            if (entity != null) throw new Exception("已存在路由路径");

            var curUser = await GetUser(curUserId);
            entity = _mapper.Map<OcelotGateway>(dto);

            var i = await InsertData(curUser, entity);
            if (i == 1)
                return _mapper.Map<OcelotGatewayView>(entity);

            throw new Exception("添加失败");
        }

        public async Task<OcelotGatewayView> Update(string curUserId, OcelotGatewayUpdateDto dto)
        {
            var entity = await GetUpdateEntity(dto.Id, dto.TimeStamp);

            var curUser = await GetUser(curUserId);
            entity = _mapper.Map(dto, entity);

            var i = await UpdateData(curUser, entity);
            if (i == 1)
                return _mapper.Map<OcelotGatewayView>(entity);

            throw new Exception("更新失败");
        }

        public async Task<List<OcelotGatewayView>> Delete(string curUserId, List<string> ids)
        {
            var curUser = await GetUser(curUserId);
            var list = await GetListAsync(t => ids.Contains(t.Id));

            UseTrans(async () =>
            {
                await DeleteDataL(curUser, list);
            });

            return _mapper.Map<List<OcelotGatewayView>>(list);
        }

        public async Task<PagedResult<OcelotGatewayView>> Search(OcelotSearchRequest req)
        {
            var query = AsQueryable();
            if (req.GatewaySys != null)
                query = query.Where(t => t.GatewaySys == req.GatewaySys);

            RefAsync<int> total = 0;
            var data = await query.ToPageListAsync(req.PageIndex, req.PageSize, total);

            return new PagedResult<OcelotGatewayView>
            {
                Total = total.Value,
                Items = _mapper.Map<List<OcelotGatewayView>>(data)
            };
        }
    }
}
